<template>
    <div class="content" id="scrollContainer" :style="{
        'overflow-y': showScrollBar ? 'auto' : 'hidden'
    }">
        <slot />
    </div>
</template>

<script>
export default {
    name: 'scrollAutoCom',
    props: {
        showScrollBar: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            speed: 0.2, // 滚动速度
            scrollPosition: 0, // 滚动位置
            animationFrameId: null, // 动画方法 与 setTimeout 类似可用于取消动画
            container: null // 外层盒子实例
        }
    },
    methods: {
        // 开始滚动
        startScroll() {
            this.animationFrameId = requestAnimationFrame(() => {
                this.scrollPosition += this.speed;
                if (this.scrollPosition > this.container.scrollHeight - this.container.clientHeight) {
                    this.scrollPosition = 0;
                }
                this.container.scrollTop = this.scrollPosition;
                this.startScroll(); // Continue animation
            });
        },
        // 初始化
        initialize() {
            this.startScroll();
            this.container.addEventListener('mouseover', this.stopScroll);
            this.container.addEventListener('mouseout', this.startScroll);
        },
        // 停止滚动
        stopScroll() {
            if (this.animationFrameId) {
                cancelAnimationFrame(this.animationFrameId);
            }
        }
    },
    mounted() {
        this.container = document.getElementById('scrollContainer')
        this.initialize()
    },
    // 不显示时暂停
    beforeDestroy() {
        cancelAnimationFrame(this.animationFrameId);
    },
    // 不显示时暂停
    deactivated() {
        cancelAnimationFrame(this.animationFrameId);
    }
}
</script>

<style lang="scss" scoped>
.content {
    position: relative;
}
</style>